<template>
  <view class="image-wrapper">
    <image class="image" :src="currentImageSrc" @click="handleClick" />
  </view>
</template>

<script setup lang="ts">
import { computed, ref, watch, onBeforeUnmount } from "vue";
import env from "@/config/env";
import { AudioManager } from "@/utils/AudioManager";

interface IProps {
  staticImageSrc: string;
  animatedImageSrc: string;
  voice?: string;
  isAutoPlay?: boolean; // 是否自动播放
  isPlay?: boolean; //手动控制动画，isAutoPlay为false生效
  isContinued?: boolean; // 是否持续播放
}

const emits = defineEmits<{
  (e: "onVoiceStart"): void;
  (e: "onVoiceStop"): void;
  (e: "onVoiceEnded"): void;
  (e: "onClick"): void;
  (e: "onContinued"): void;
}>();

const props = withDefaults(defineProps<IProps>(), {
  staticImageSrc: "https://rwstatic.tentons.cn/web/Lesson/images/loudspeaker-static.png",
  animatedImageSrc: "https://rwstatic.tentons.cn/web/Lesson/images/loudspeaker.png",
  isAutoPlay: false,
  isPlay: false,
  isContinued: false,
});

const isPlay = ref(false);
const isAudioStop = ref(false);

const currentImageSrc = computed(() => {
  return isPlay.value ? props.animatedImageSrc : props.staticImageSrc;
});

uni.$on("is-audio-play", res => {
  isAudioStop.value = res.isAudioStop;
});

const handleClick = () => {
  emits("onClick");

  if (!props.voice || isAudioStop.value) {
    return;
  }

  if (props.isContinued) {
    if (isPlay.value) {
      emits("onContinued");
    }
  }

  AudioManager.getInstance().play({
    src: `${env.prefixUrl}${props.voice}`,
    onVoiceStart: () => {
      isPlay.value = true;
      emits("onVoiceStart");
    },
    onVoiceStop: () => {
      isPlay.value = false;
      emits("onVoiceStop");
    },
    onVoiceEnded: () => {
      isPlay.value = false;
      emits("onVoiceEnded");
    },
  });
};

watch(
  () => props.voice,
  (val) => {
    if (val && props.isAutoPlay) {
      handleClick();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => props.isPlay,
  (val) => {
    if (props.isAutoPlay) {
      return;
    }
    isPlay.value = props.isPlay;
  },
  {
    deep: true,
    immediate: true,
  }
);

onBeforeUnmount(() => {
  AudioManager.getInstance().stop();
  uni.$off("is-audio-play");
});

defineExpose({
  handleClick,
})
</script>

<style scoped lang="scss">
.image-wrapper {
  width: 100%;
  height: 100%;

  .image {
    width: 100%;
    height: 100%;
  }
}
</style>
